import json
import os
import random
import time
from datetime import datetime

from flask import Flask, render_template, request, jsonify, session
from orm.persistence.ChatUtil import *
from orm.entity.Chat import Chat

from orm.persistence.DormitoryUtil import getDormitoryInformationById
from orm.persistence.OtherUtil import getAllUserIdNotInDormitory, addNewLocation
from orm.service.impl.UserServiceImpl import userRegister, userSearchById, userUpdate, userDeleteByUserId
from orm.service.impl.DormitoryServiceImpl import *

localtime = time.localtime(time.time())
time = str(localtime.tm_year) + "-" + str(localtime.tm_mon) + "-" + str(localtime.tm_mday)
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)


@app.route('/')
def index():
    if request.method == 'GET':
        return render_template('index.html')


@app.route('/getSession', methods=['GET', 'POST'])
def getSession():
    data = {'userid': session.get('userid'), 'username': session.get('username'),
            'password': session.get('password'), 'phone_number': session.get('phone_number'),
            'dormitoryId': session.get('dormitoryId'), 'admin': session.get('admin'),
            'user1Id': session.get('user1Id'), 'user2Id': session.get('user2Id'), 'user3Id': session.get('user3Id'),
            'user4Id': session.get('user4Id'),
            'user1Name': session.get('user1Name'), 'user2Name': session.get('user2Name'),
            'user3Name': session.get('user3Name'), 'user4Name': session.get('user4Name'),
            'user1Phone': session.get('user1Phone'), 'user2Phone': session.get('user2Phone'),
            'user3Phone': session.get('user3Phone'), 'user4Phone': session.get('user4Phone'),
            'isInDormitory': session.get('isInDormitory'), 'isInDormitory1': session.get('isInDormitory1'),
            'isInDormitory2': session.get('isInDormitory2'), 'isInDormitory3': session.get('isInDormitory3'),
            'isInDormitory4': session.get('isInDormitory4')
            }
    return jsonify(data)


# GET说明是获取网页
# POST是传递表单
@app.route('/login/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login/login.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        userid = data['userid']
        password = data['password']
        user = userSearchById(userid)
        dormitory = getDormitoryInformationById(user.dormitoryId)
        user1 = userSearchById(dormitory.user1)
        user2 = userSearchById(dormitory.user2)
        user3 = userSearchById(dormitory.user3)
        user4 = userSearchById(dormitory.user4)

        if user is None:
            return jsonify('用户名不存在！')
        elif user.password == password:
            session['userid'] = user.userId
            session['username'] = user.userName
            session['password'] = user.password
            session['phone_number'] = user.phone_number
            session['dormitoryId'] = user.dormitoryId
            session['admin'] = user.isAdmin
            if user1 is not None:
                session['user1Id'] = user1.userId
                session['user1Name'] = user1.userName
                session['user1Phone'] = user1.phone_number
                if getAllUserIdNotInDormitory(time).__contains__(user1.userId):
                    session['isInDormitory1'] = 0
                else:
                    session['isInDormitory1'] = 1
            if user2 is not None:
                session['user2Id'] = user2.userId
                session['user2Name'] = user2.userName
                session['user2Phone'] = user2.phone_number
                if getAllUserIdNotInDormitory(time).__contains__(user2.userId):
                    session['isInDormitory2'] = 0
                else:
                    session['isInDormitory2'] = 1
            if user3 is not None:
                session['user3Id'] = user3.userId
                session['user3Name'] = user3.userName
                session['user3Phone'] = user3.phone_number
                if getAllUserIdNotInDormitory(time).__contains__(user3.userId):
                    session['isInDormitory3'] = 0
                else:
                    session['isInDormitory3'] = 1
            if user4 is not None:
                session['user4Id'] = user4.userId
                session['user4Name'] = user4.userName
                session['user4Phone'] = user4.phone_number
                if getAllUserIdNotInDormitory(time).__contains__(user4.userId):
                    session['isInDormitory4'] = 0
                else:
                    session['isInDormitory4'] = 1
            if getAllUserIdNotInDormitory(time).__contains__(userid):
                session['isInDormitory'] = 0
            else:
                session['isInDormitory'] = 1
            return jsonify('登录成功！')
        else:
            return jsonify('用户名或密码不正确')


@app.route('/login/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('login/register.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        userid = data['userid']
        username = data['username']
        phone = data['phone']
        dormitory = data['dormitory']
        password = data['password']
        state = userRegister(userid, username, password, phone, dormitory)
        print(state)
        if state == 0:
            return jsonify("成功注册")
        elif state == 1:
            return jsonify("学号已经存在")
        elif state == 2:
            return jsonify("宿舍已满")
        elif state == 3:
            return jsonify("宿舍不存在")
        return jsonify("发生了未知错误，请联系管理员")


@app.route('/login/forgotPassword', methods=['GET', 'POST'])
def forgotPassword():
    if request.method == 'GET':
        return render_template('login/forgot-password.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        userid = data['userid']
        user = userSearchById(userid)
        if user is None:
            return jsonify("没有此学号")
        else:
            pin = random.randint(999, 9999)

            return jsonify({'pin': pin, 'phone': user.phone_number})


@app.route('/login/recoverPassword', methods=['GET', 'POST'])
def recoverPassword():
    if request.method == 'GET':
        return render_template('login/recover-password.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        password = data['password']
        verificationCode = data['verificationCode']
        vercode = data['vercode']
        userid = data['userid']
        if verificationCode == vercode:
            # 更改密码
            user = userSearchById(userid)
            print(userUpdate(userid, user.userName, password, user.phone_number, user.dormitoryId))
            return jsonify("修改成功！")
        else:
            return jsonify("验证码错误！")


@app.route('/monitor/main', methods=['GET'])
def monitorMain():
    if request.method == 'GET':
        return render_template('monitor/main.html')


@app.route('/monitor/adminMaintenance', methods=['GET', 'Post'])
def adminMaintenance():
    if request.method == 'GET':
        dormitories = getAllDormitoryInformation()
        return render_template('monitor/adminMaintenance.html', dormitories=dormitories)
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        print(data)
        dormitoryId = data['dormitoryId']
        if data['action'] == "delete":
            if deleteDormitory(dormitoryId):
                return jsonify("删除成功")
            else:
                return jsonify("删除失败")


@app.route('/monitor/personalInformation', methods=['GET', 'POST'])
def personalInformation():
    if request.method == 'GET':
        return render_template('monitor/personalInformation.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        userid = data['userid']
        print(data)
        if data['action'] == "delete":
            userDeleteByUserId(userid)
            return jsonify("")
        elif data['action'] == "change":
            user = userSearchById(userid)
            if userUpdate(userid, user.userName, data['changePassword'], data['changePhone'], data['changeDormitory']):
                session['password'] = data['changePassword']
                session['phone_number'] = data['changePhone']
                session['dormitoryId'] = data['changeDormitory']
                return jsonify("更新成功")
            else:
                return jsonify("更新失败")


@app.route('/monitor/sleepCheck', methods=['GET', 'POST'])
def sleepCheck():
    if request.method == 'GET':
        return render_template('monitor/sleepCheck.html')
    if request.method == 'POST':
        data = json.loads(request.form.get('data'))
        time = str(localtime.tm_year) + "-" + str(localtime.tm_mon) + "-" + str(localtime.tm_mday)
        print(data['dormitoryId'], data['userid'], time)
        addNewLocation(data['dormitoryId'], data['userid'], time)
        session['isInDormitory'] = 1
        user = userSearchById(data['userid'])
        dormitory = getDormitoryInformationById(user.dormitoryId)
        user1 = userSearchById(dormitory.user1)
        user2 = userSearchById(dormitory.user2)
        user3 = userSearchById(dormitory.user3)
        user4 = userSearchById(dormitory.user4)
        if user1 is not None:
            if getAllUserIdNotInDormitory(time).__contains__(user1.userId):
                session['isInDormitory1'] = 0
            else:
                session['isInDormitory1'] = 1
        if user2 is not None:
            if getAllUserIdNotInDormitory(time).__contains__(user2.userId):
                session['isInDormitory2'] = 0
            else:
                session['isInDormitory2'] = 1
        if user3 is not None:
            if getAllUserIdNotInDormitory(time).__contains__(user3.userId):
                session['isInDormitory3'] = 0
            else:
                session['isInDormitory3'] = 1
        if user4 is not None:
            if getAllUserIdNotInDormitory(time).__contains__(user4.userId):
                session['isInDormitory4'] = 0
            else:
                session['isInDormitory4'] = 1

        return jsonify("打卡成功")


@app.route('/monitor/door', methods=['GET'])
def door():
    if request.method == 'GET':
        return render_template('monitor/monitor/door.html')


@app.route('/monitor/infra-red', methods=['GET'])
def infraRed():
    if request.method == 'GET':
        return render_template('monitor/monitor/infra-red.html')


@app.route('/monitor/temperatureAndHumidity', methods=['GET'])
def temperatureAndHumidity():
    if request.method == 'GET':
        return render_template('monitor/monitor/temperatureAndHumidity.html')


@app.route('/monitor/chat', methods=['GET'])
def chat():
    dormitoryId = session.get('dormitoryId')
    chats = getChats(dormitoryId)
    # print(len(chats))
    return render_template('monitor/chat.html', chats=chats, userId=session.get("userid"))


@app.route('/monitor/ALLchats', methods=['GET'])
def ALLchats():
    dormitoryId = session.get('dormitoryId')
    chats = getAllChats(dormitoryId)
    print(len(chats))
    return render_template('monitor/chat.html', chats=chats, userId=session.get("userid"))


@app.route('/monitor/makeChat', methods=['POST'])
def makeNewChat():
    dormitoryId = session.get('dormitoryId')
    speaker = session.get('userid')
    date = datetime.now()
    text = request.form.get('text')
    print(text)
    chat = Chat(dormitoryId, speaker, date, text)
    makeChat(chat)
    chats = getChats(dormitoryId)
    # print(len(chats))
    return "ok"


if __name__ == '__main__':
    app.run(debug=True)
